import React, { useState } from 'react';

import './App.css';

import { formatPrice } from "./utils/format-utils";
import { IBookListType } from "./type";

function App() {
  const theadList: string[] = ["序号", "书籍名称", "出版日期", "价格", "购买数量", "操作"];
  const [bookList, setbookList] = useState<Array<IBookListType>>([
    { id: 1, name: '<越狱>', date: '2022/5/9', price: 80, count: 1},
    { id: 2, name: '<纸牌屋>', date: '2022/5/8', price: 120, count: 1},
    { id: 3, name: '<绝命毒师>', date: '2022/5/9', price: 220, count: 1},
    { id: 4, name: '<浴血黑帮>', date: '2022/5/8', price: 60, count: 1},
    { id: 5, name: '<指环王>', date: '2022/5/9', price: 100, count: 1},
  ]);

  //1.计算总价格
  const getTotalPrice = (): string => {
    const totalPrice = bookList.reduce((pre, item) => {
      return pre + item.price * item.count;
    }, 0);

    return formatPrice(totalPrice);
  };

  //2.改变书籍数量
  const changeBooksCount = (index: number, num: number) => {
    const newBooks = [...bookList];
    newBooks[index].count += num;
    setbookList(newBooks);
  };

  //3.移除书籍
  const handleDelete = (index: number) => {
    setbookList(bookList.filter((item, indey) => index !== indey));
  };

  return (
    <div className="App">
      <table>
        <thead>
          <tr>
            {
              theadList.map(item => <th key={item}>{item}</th>)
            }
          </tr>
        </thead>

        <tbody>
          {
            bookList.map((item, index) => {
              return (
                <tr key={item.id}>
                  <td>{index + 1}</td>
                  <td>{item.name}</td>
                  <td>{item.date}</td>
                  <td>{formatPrice(item.price)}</td>
                  <td>
                    <button 
                    onClick={e => changeBooksCount(index, -1)}
                    disabled={item.count <= 1}
                    >
                      -1
                    </button>
                    <span>{item.count}</span>
                    <button
                     onClick={e => changeBooksCount(index, 1)}
                    >
                       +1
                    </button>
                  </td>
                  <td>
                    <button
                      onClick={e => handleDelete(index)}
                    >
                      移除
                    </button>
                  </td>
                </tr>
              )
            })
          }
        </tbody>
      </table>

      <h2>总价格：{getTotalPrice()}</h2>
    </div>
  );
}

export default App;
